<link rel="stylesheet" href="/css/element.css">
<script src="/js/Vue.js"></script>
<script src="/js/element.js"></script>
<script src="/js/axios.js"></script>
<script src="/js/formDataUtils.js"></script>
<script src="/js/jquery.min.js"></script>
<style>
    #tools .el-card__body {
        padding: 5px 5px 5px 20px;
    }
    .el-link {
        margin-right:8px;
    }
    #tools .el-button {
        padding: 10px 8px 10px 5px;
    }
    #template {
        height:100%;
    }
    /* #search .el-card__body {
        height:40px;
    } */
    #table {
        height:calc(100% - 120px);
    }
    /*翻页样式*/
    .el-pagination {
        margin-top:5px;
    }
    #tools .el-button {
        padding: 10px 8px 10px 5px;
        background-color:whitesmoke !important;
        color: black !important;
        border: none !important;
      }
      .el-form-item label{
        text-align: left !important;
        width: 68px !important;
        vertical-align: middle;
        float: left;
        font-size: 14px;
        color: #606266;
        line-height: 40px;
        padding: 0 12px 0 0;
        -webkit-box-sizing: border-box;
        box-sizing: border-box;
      }
</style>
<div id="template">
    <!--    用户查询框-->
    <el-card class="box-card" id="search" prop="editor">
        <el-form :inline="true" class="demo-form-inline">
            <el-form-item label="机构名称">
                <el-input clearable placeholder="请输入要查询的内容" style="width:200px;" v-model="asName"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button size="medium" type="primary" size="large" @click="searchAllSceneHandle">查询</el-button>
            </el-form-item>
        </el-form>
    </el-card>
    <!--工具栏-->
    <el-card id="tools">
        <el-row>
            <el-button size="small" icon="el-icon-document-add"  type="primary" @click="addSceneAction">
                添加
            </el-button>
            <el-button size="small" icon="el-icon-document-add"  type="danger" @click="addNew">新建
            </el-button>
            <el-button size="small" icon="el-icon-document-add"  type="danger" @click="userDelete">导入
            </el-button>
        </el-row>
    </el-card>
    <!--    查询数据展示表格-->
    <el-card id="table">
        <el-table
                border
                :stripe="true"
                ref="multipleTable"
                :key="updatakey"
                :data="tableData"
                tooltip-effect="dark"
                style="width: 100%"
                @selection-change="handleSelectionChange"
                :select-on-indeterminate="false">
            <el-table-column
                    type="selection">
            </el-table-column>
            <el-table-column
                    prop="name"
                    align="center"
                    label="机构名称"
                    width="150">
            </el-table-column>
            <el-table-column
                    prop="id"
                    label="机构编码"
                    align="center"
                    show-overflow-tooltip>
            </el-table-column>
            <!--            操作-->
            <el-table-column label="操作" align="center" width="320">
                <template slot-scope="scope">
                    <!-- "isTemplate"为true 则显示 编辑模板按钮-->
                    <el-link @click="sceneNameEditAction(scope.$index, scope.row)" type="success">修改</el-link>
                    <el-link v-if="scope.row.isTemplate" @click="editSceneAction(scope.$index,scope.row.editor)" type="primary" icon="layui-icon-edit">编辑</el-link>
                    <el-popconfirm title="确定要删除吗？" @confirm="deleteCompany(scope.$index, scope.row)">
                        <el-link slot="reference" type="danger" icon="layui-icon-delete">删除</el-link>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <!--        页码-->
        <el-pagination
                background
                @current-change="handleCurrentChange"
                :prev-click='prevOnePage'
                :next-click="nextOnePage"
                :current-page="currentPage"
                :page-size="pageSize"
                layout="total,prev, pager, next, jumper"
                :total="totaldata">
        </el-pagination>
    </el-card>
</div>
<script>
    Vue.config.productionTip = false;//屏蔽提示信息
    //当前编辑的场景数据
    var sceneData = {};
    //场景id
    var sceneId;
    var addwindow = null;
    var editwindow = null;
    var addname;
    var editname;
    var tem = new Vue({
        el: "#template",
        data() {
            return {
                totaldata:3,
                multipleSelection: [],//多选数组
                asName:"",
                updatakey:false,
                id:"",
                unit:"",
                department:"",
                state:"",
                wstate:"",
                admin:"",
                user:"",
                currentPage: 1,//当前页码
                pageSize: 10,//默认每一页数量
                //编辑场景-编辑指令-数据
                editOrderData: {},
                tableData:[
                ]

            }
        },
        filters: {
            //是否为模板
            isTemplate(val) {
                if (val) {
                    return "是"
                } else {
                    return "否"
                }
            },
            //场景状态过滤
            sceneStatus(val) {
                if (val == 0) {
                    return "场景模板"
                } else if (val == 1) {
                    return "新建"
                } else {
                    return "绑定角色"
                }
            },
        },
        mounted() {
            const that = this;
            //查询所有的场景
            this.searchAllScene();
        },
        methods: {
            //手动查询
            searchAllSceneHandle(){
                if(this.asName == ""){
                    this.$message.error("请输入机构名称！");
                    return false;
                }else {
                    this.searchAllScene();
                }
            },
            //导入
            userDelete(){
                layer.open({
                    type: 2,
                    title: '导入',
                    shadeClose: true,
                    shade: false,
                    maxmin: true, //开启最大化最小化按钮
                    area: ['400px', '400px'],
                    content: '/',
                    end: () => {
                        this.searchAllScene();
                        sceneData = {};
                    }
                });
            },
            //新建
            addNew(){
                layer.open({
                    type: 2,
                    title: '新建',
                    shadeClose: true,
                    shade: false,
                    maxmin: true, //开启最大化最小化按钮
                    area: ['400px', '400px'],
                    content: '/',
                    end: () => {
                        this.searchAllScene();
                        addNew = {};
                    }
                }); 
            },
            userDelete() {
                const that = this;
                if (this.multipleSelection.length >= 1) {
                    layer.confirm('确定要删除吗？', {icon: 3, title: '警告'}, function (index) {
                        //重组 参数：id（数组）
                        let list = that.multipleSelection;
                        let result = [];
                        for (let i = 0; i < list.length; i++) {
                            result.push(list[i].id);
                        }
                        let param = new FormData();
                        param.append('id', result);
                        axios.post('/scene/delete', param).then(res => {
                            if (res.data.success) {
                                that.$message.success("删除成功！");
                                that.deleteCorrect(that.tableData,result.length);
                                //刷新表格数据
                                that.searchAllScene();
                            } else {
                                that.$message.error(res.data.message);
                            }
                        }).catch(err => {
                            console.log(err);
                        });
                        //关闭提醒框
                        layer.close(index);
                    });
                } else {
                    layer.alert("请勾选场景后再点击删除！");
                }
            },
            //下一页
            nextOnePage(val) {
                this.currentPage = val;
                //刷新表格数据
                this.searchAllScene();
            },
            //上一页
            prevOnePage(val) {
                this.currentPage = val;
                //刷新表格数据
                this.searchAllScene();
            },
            //翻页change事件
            handleCurrentChange(val) {
                this.currentPage = val;
            },
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            //查询所有场景
            searchAllScene() {
                let params = {
                    name:this.asName,
                    page: this.currentPage,
                    pageSize: this.pageSize
                }
                //这个方法无法使用获取的对象是object
                // axios.get('/syatem/query_company', {params}).then(res => {
                //     //给表格赋值
                //     //let rows1=eval('(' + res + ')');;
                //     let rows1=eval('(' + res.data + ')');;
                //     console.log(typeof(res.data));
                   

                //     console.log('res:'+rows1);
                //     //this.tableData = rows1.data.content;
                //     //this.deleteCorrect2(this.tableData);
                // }).catch(err => {
                //     console.log(err);
                // })
                var that = this;
            $.get('syatem/query_company', params, function (data) {
                    //console.log(data);
                    that.tableData = data.data.content;
                    that.totaldata = data.data.totalElements;
                    //console.log(data.data.content);
                    console.log('现在数据长度是:'+that.totaldata);
                    //刷新表格
                    that.updatakey=!this.updatakey;
                })
             },
             //新建部门
            addNewCompany(companyname) {
                let params = {
                    name:companyname,
                }
                var that = this;
            $.post('syatem/add_company', params, function (data) {
                    //console.log(data);
                    if(data.success)
                    {
                        console.log('sucess~');
                        that.searchAllScene();
                        that.updatakey=!this.updatakey;
                    }
                    else 
                    {
                        console.log('error!!!'+data.message);
                    }
                    //console.log(data.data.content);
                    //刷新表格
                })
             }, 
            //新建部门弹出窗口
            addSceneAction() {
                //打开弹窗
                var that = this;
               addwindow = layer.open({
                    type: 2,
                    title: '添加',
                    shadeClose: true,
                    shade: false,
                    maxmin: false, //开启最大化最小化按钮
                    area: ['400px', '400px'],
                    content: '/dialog/system/addcompany.html',
                    cancel: function () {
                        addname='';
                        console.log('cancel...')
              },
                    end: () => {
                        if(addname)
                        {
                            console.log('增加机构名称:'+addname);
                            this.addNewCompany(addname);
                        }
                        else 
                        {
                            console.log('end...')
                        }
                        //this.searchAllScene();
                        //sceneData = {};
                    }
                });
            },
            //最后一页最后一条数据删除时，页码纠正
            deleteCorrect(data,number){
                const totalPage = Math.ceil((data.length - number) / this.pageSize) // 总页数
                this.currentPage = this.currentPage > totalPage ? totalPage : this.currentPage
                this.currentPage = this.currentPage < 1 ? 1 : this.currentPage
            },
            //查询页码纠正
            deleteCorrect2(data){
                const totalPage = Math.ceil(data.length / this.pageSize) // 总页数
                this.currentPage = this.currentPage > totalPage ? totalPage : this.currentPage
                this.currentPage = this.currentPage < 1 ? 1 : this.currentPage
            },
            //逐行删除场景
            rowDelete(index, row) {
                let param = new FormData();
                let array = [row.id];
                param.append('id', array);
                axios.post('/data/add_job', param).then(res => {
                    if (res.data.success) {
                        this.$message.success("删除成功！");
                        this.deleteCorrect(this.tableData,1);
                    } else {
                        this.$message.error(res.data.message);
                    }
                    //刷新表格数据
                    this.searchAllScene();
                }).catch(err => {
                    console.log(err);
                })
            },

            //单条删除部门     
            deleteCompany(index, row) {
                console.log('del'+'id:'+row.id+'name:'+row.name);
                var that = this;
                let params = 
                {
                    id:row.id,
                    name:row.name,
                }
                $.post('syatem/delete_company', params, function (data) {
                    //console.log(data);
                    if(data.success)
                    {
                        alert("机构成功删除");
                        //console.log('sucess~');
                        that.searchAllScene();
                        that.updatakey=!this.updatakey;
                    }
                    else 
                    {
                        console.log('error!!!'+data.message);
                    }
                    //console.log(data.data.content);
                    //刷新表格
                })
             },
            //编辑部门
            editCompany(companyid,companyname) {
                let params = {
                    id:companyid,
                    name:companyname,
                }
                var that = this;
            $.post('syatem/update_company', params, function (data) {
                    //console.log(data);
                    if(data.success)
                    {
                        console.log('sucess~');
                        that.searchAllScene();
                        that.updatakey=!this.updatakey;
                    }
                    else 
                    {
                        console.log('error!!!'+data.message);
                    }
                    //console.log(data.data.content);
                    //刷新表格
                })
             },
            //弹出编辑窗口
            sceneNameEditAction(index, row) {
                //场景id赋值
                //console.log(index);
                console.log(row);
                sceneId = row.id;
                //数据回显赋值
                sceneData = row;
                //打开弹窗
                editwindow=layer.open({
                    type: 2,
                    title: '修改',
                    shadeClose: true,
                    shade: false,
                    maxmin: true, //开启最大化最小化按钮
                    area: ['400px', '400px'],
                    content: '/dialog/system/editcompany.html',
                    cancel: function () {
                        editname='';
                        console.log('cancel...')
              },
                    end: () => {
                        if(editname)
                        {
                            console.log('更新机构名称:'+editname+'ID:'+sceneId);
                            this.editCompany(sceneId,this.asName);
                            //this.addNewCompany(addname);
                        }
                        else 
                        {
                            console.log('end...')
                        }
                        //this.searchAllScene();
                        //sceneData = {};
                    }
                });
            },
            //弹出场景窗口
            editSceneAction(index, row) {
                sceneData = row;
                sceneData.sceneName = row.sceneName;
                //打开弹窗
                // layer.open({
                //     type: 1,
                //     title: '编辑',
                //     shadeClose: true,
                //     shade: false,
                //     maxmin: true, //开启最大化最小化按钮
                //     area: ['1000px', '600px'],
                //     content: '/dialog/system/organization/html',
                // });
                console.log()
            }
        }
    })
</script>